﻿using Donal.Xms.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
using ThoughtWorks.QRCode.Codec;

namespace Donal.Xms.Web.tools
{
    /// <summary>
    /// QRCode 生成类
    /// </summary>
    public class QRCode : IHttpHandler, IRequiresSessionState
    {
        Model.sysconfig sysConfig = new BLL.sysconfig().loadConfig();
        public void ProcessRequest(HttpContext context)
        {
            //取得处事类型
            string action = DTRequest.GetQueryString("action");

            if (action.LastIndexOf("_") > 0)
            {
                action = action.Substring(0, action.LastIndexOf("_"));
            }

            switch (action)
            {
                case "GetQRCode": //向页面输入二维码流，用于页面显示
                    Get_QRCode(context);
                    break;
                case "SaveQRCode": //保存生成的二维码到指定目录
                    SaveQRCode(context);
                    break;
            }
        }

        #region 保存生成的二维码到指定目录

        private void SaveQRCode(HttpContext context)
        {
            string channel_name = DTRequest.GetFormString("name");
            if (channel_name.Trim() == "")
            {
                context.Response.Write("{\"status\":0, \"msg\":\"生成失败 代码:001\"}");
                return;
            }

            string link_url = sysConfig.weburl;
            string _paht = new BLL.sysconfig().loadConfig().webpath + sysConfig.filepath;
            string qrcode_path = _paht + "/QrCode/";
            string zip_path = _paht + "/Zips/";
            string zip_filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip";
            string[] FileProperties = new string[2];
            string path1 = Utils.GetMapPath(zip_path);
            string path0 = Utils.GetMapPath(qrcode_path);//待压缩文件目录
            string zipPath = path1 + zip_filename;  //压缩后的目标文件                 

            Utils.CreatePathAndClearFiles(path0);
            Utils.CreatePathAndClearFiles(path1);

            //这里的ds是将要生成二维码的数据，要根据实际查找。
            DataSet ds = new BLL.common().GetList("select id,restaurants_id,table_no,area_id FROM dt_tables ");
            
            Donal.Xms.Web.UI.BasePage basePage = new UI.BasePage();

            if (Utils.CheckDataSet(ds))
            {
                int index = 0;
                int count = ds.Tables[0].Rows.Count;
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    ++index;

                    string content = link_url + basePage.linkurl(0,"cus_ordering", DESEncrypt.Encrypt(DateTime.Now.ToString("yyMMddHHmmssms") + "_" + dr["id"].ToString() + "_" + dr["restaurants_id"].ToString() + "_" + DateTime.Now.ToString("yyMMddHHmmssms")));
                    int size = 237;
                    int border = 1;

                    System.Drawing.Image image = QRCodeHelper.CreateQRCode(content,
                        QRCodeEncoder.ENCODE_MODE.BYTE,
                        QRCodeEncoder.ERROR_CORRECTION.M,
                        0,
                        5,
                        size,
                        border);

                    //将画像输出到页面                     
                    image.Save(path0 + dr["table_no"].ToString() + ".Png", ImageFormat.Png);
                    image.Dispose();
                    image = null;
                }

                if (ZipHelper.ZipFile(path0, zipPath))
                {
                    context.Response.Write("{\"status\":1, \"msg\":\"" + zip_filename + "\"}");
                    return;
                }
                else
                {
                    context.Response.Write("{\"status\":0, \"msg\":\"生成失败\"}");
                    return;
                }
            }
            else
            {
                context.Response.Write("{\"status\":0, \"msg\":\"没找到数据，生成失败！\"}");
                return;
            }
        }

        #endregion

        #region 向页面输入二维码流，用于页面显示

        private void Get_QRCode(HttpContext context)
        {
            string queryString = DTRequest.GetQueryString("data");
            if (string.IsNullOrEmpty(queryString))
            {
                queryString = Utils.GetCookie("imglink");
                if (string.IsNullOrEmpty(queryString))
                {
                    return;
                }
            }
            QRCodeEncoder encoder = new QRCodeEncoder
            {
                QRCodeVersion = 0
            };
            MemoryStream stream = new MemoryStream();
            encoder.Encode(queryString, Encoding.UTF8).Save(stream, ImageFormat.Gif);
            context.Response.ClearContent();
            context.Response.ContentType = "image/Gif";
            context.Response.BinaryWrite(stream.ToArray());
            context.Response.End();
        }

        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
